package com.quectel.core.module.help.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.help.HelpCenterConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.help.dao.HelpCenterDao;
import com.quectel.core.module.help.dao.HelpCenterVillageDao;
import com.quectel.core.module.help.dto.HelpCenterDto;
import com.quectel.core.module.help.dto.HelpCenterVillageDto;
import com.quectel.core.module.help.entity.HelpCenterEntity;
import com.quectel.core.module.help.entity.HelpCenterVillageEntity;
import com.quectel.core.module.help.service.HelpCenterService;
import com.quectel.core.module.help.service.HelpCenterVillageService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/04/24 18:38
 */
@DubboService
public class HelpCenterServiceImpl implements HelpCenterService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelpCenterServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> HELP_CENTER_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "HELP_CENTER_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<HelpCenterDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(HELP_CENTER_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private HelpCenterDao helpCenterDao;
    @Autowired
    private HelpCenterVillageDao helpCenterVillageDao;
    @Autowired
    private HelpCenterVillageService helpCenterVillageService;


    @Override
    public List<HelpCenterDto> queryListByUnionDirect(Map<String, Object> params) {
        List<HelpCenterEntity> list = helpCenterDao.queryListByUnionDirect(params);
        List<HelpCenterDto> result = CopyUtils.copyList(list, HelpCenterDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public int queryTotalByUnionDirect(Map<String, Object> params) {
        return helpCenterDao.queryTotalByUnionDirect(params);
    }

    @Override
    public void saveOrUpdate(HelpCenterDto helpCenterDto) {
        if (helpCenterDto.getId() == null) {
            Long id = save(helpCenterDto);
            helpCenterDto.setId(id);
        } else {
            updateById(helpCenterDto);
        }

        // 删除绑定关系
        helpCenterVillageDao.delete(new LambdaQueryWrapper<HelpCenterVillageEntity>()
                .eq(HelpCenterVillageEntity::getHelpCenterId, helpCenterDto.getId()));

        // 定向到小区的绑定下小区信息
        if (HelpCenterConstants.DirectType.DIRECT.getType().equals(helpCenterDto.getDirectType())) {
            for (VillageDto village : helpCenterDto.getVillageList()) {
                HelpCenterVillageDto helpCenterVillage = new HelpCenterVillageDto();
                helpCenterVillage.setId(Snowflake.nextId());
                helpCenterVillage.setHelpCenterId(helpCenterDto.getId());
                helpCenterVillage.setTenantId(helpCenterDto.getTenantId());
                helpCenterVillage.setVillageId(village.getId());
                helpCenterVillageService.save(helpCenterVillage);
            }
        }
    }

    @Override
    public HelpCenterDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                HELP_CENTER_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public HelpCenterDto selectById(Long id) {
        HelpCenterEntity entity = helpCenterDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, HelpCenterDto.class));
    }

    @Override
    public List<HelpCenterDto> queryList(Map<String, Object> params) {
        List<HelpCenterEntity> list = helpCenterDao.queryList(params);
        List<HelpCenterDto> result = CopyUtils.copyList(list, HelpCenterDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private HelpCenterDto paddingField(HelpCenterDto dto) {
        if (dto != null) {

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return helpCenterDao.queryTotal(params);
    }

    @Override
    public Long save(HelpCenterDto dto) {
        HelpCenterEntity entity = CopyUtils.copyObj(dto, HelpCenterEntity.class);
        entity.setId(Snowflake.nextId());
        helpCenterDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(HelpCenterDto dto) {
        HelpCenterEntity entity = CopyUtils.copyObj(dto, HelpCenterEntity.class);

        helpCenterDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(HelpCenterDto dto) {
        HelpCenterEntity entity = CopyUtils.copyObj(dto, HelpCenterEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, helpCenterDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        helpCenterDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
